﻿using ERP.Web.Core.Model;
using ERP.Web.Core.Pocket;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Generic;
using System.Linq;

namespace ERP.Web.Core.Facade
{
    public class CustomResultFilter : IResultFilter
    {
        public void OnResultExecuted(ResultExecutedContext context)
        {

        }

        public void OnResultExecuting(ResultExecutingContext context)
        {

            if (context.Controller is ApiControllerBase api && context.ActionDescriptor is ControllerActionDescriptor action)
            {
                var objResult = context.Result as ObjectResult;
                var dict = new Dictionary<string, object>
                {
                    { api.OutputDataDefaultFieldName, objResult?.Value }
                };
                var pocketAttrs = action.RetrieveCustomAttribute<PocketAttribute>();

                var pockets = pocketAttrs.Select(p => p.ObtainResult(context.HttpContext)).ToDictionary(p => p.Item1, p => p.Item2);
                if (pockets.Any())
                {
                    dict.Add(api.OutputPocketDefaultFieldName, pockets);
                }
                context.Result = new ObjectResultModel(dict);
            }

        }
    }
}
